package com.water76016.ourtask.service.impl;

import com.water76016.ourtask.common.RestResult;
import com.water76016.ourtask.config.security.jwt.JwtAuthService;
import com.water76016.ourtask.config.security.jwt.JwtTokenUtil;
import com.water76016.ourtask.dto.UserDTO;
import com.water76016.ourtask.entity.User;
import com.water76016.ourtask.mapper.UserMapper;
import com.water76016.ourtask.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.util.Date;


/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author github:water76016
 * @since 2020-07-21
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    JwtAuthService jwtAuthService;

    @Autowired
    JwtTokenUtil jwtTokenUtil;

    @Autowired
    private UserMapper userMapper;

    @Override
    public RestResult register(UserDTO userDTO) {
        //加密需要把用户密码进行加密存储
        BCryptPasswordEncoder bcp = new BCryptPasswordEncoder();
        String encodePassword = bcp.encode(userDTO.getPassword());
        userDTO.setPassword(encodePassword);
        userDTO.setCreateTime(new Date());
        userDTO.setRoles("0");
        boolean flag = userMapper.register(userDTO);
        return flag ? RestResult.success() : RestResult.error();
    }

    @Override
    public RestResult login(User user, HttpServletResponse response) {
        User loginUser = jwtAuthService.login(user.getUsername(), user.getPassword());
        if (loginUser == null){
            return RestResult.error("用户名或密码错误");
        }
        //生成用户token
        String token = jwtTokenUtil.generateToken(loginUser);
        RestResult result = RestResult.success();
        //这里就已经登录成功了
        response.setHeader("Authorization", token);
        response.setHeader("Access-Control-Expose-Headers", "Authorization");
        result.put("user", loginUser);
        return result;
    }
}

    /*@Override
    public RestResult userRegister(User user) {
        return null;
    }*/
